package webgamemaker.Common;

import java.util.ArrayList;


import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.widgetideas.graphics.client.ImageLoader;

public class TileSet {
	
	public String filename;
	public String name;
	public ImageElement image;
	public int tileWidth, tileHeight;
	public ArrayList<TileData> tiles;
	public ArrayList<Callback> listCallback;
	public boolean loaded;
	
	public TileSet(int tileWidth, int tileHeight)
	{
		this.filename = "";
		this.name = "";
		this.tileWidth = tileWidth;
		this.tileHeight = tileHeight;
		tiles = new ArrayList<TileData>();
		listCallback = new ArrayList<Callback>();
	}
	
	public TileSet(String filename, int tileWidth, int tileHeight)
	{
		this.filename = filename;
		this.name = filename;
		this.tileWidth = tileWidth;
		this.tileHeight = tileHeight;
		tiles = new ArrayList<TileData>();
		listCallback = new ArrayList<Callback>();
		String urls[] = new String[1];
		urls[0]=filename;
		ImageLoader.loadImages(urls, new TileSetLoadCallback());
	}
	
	public void addLoadCallback(Callback loadCallback)
	{
		if(loaded)
			loadCallback.onCall(this);
		else listCallback.add(loadCallback);
	}
	
	public class TileSetLoadCallback implements ImageLoader.CallBack
	{
		public void onImagesLoaded(ImageElement[] imageElements) 
		{
			image = imageElements[0];
			for(int y = 0; y < image.getHeight(); y += tileHeight)
				for(int x = 0; x < image.getWidth(); x+= tileWidth)
					tiles.add(new TileData(new BaseTile(TileSet.this, x, y, tileWidth, tileHeight)));
			loaded = true;
			for(int i = 0; i < listCallback.size(); i++)
				listCallback.get(i).onCall(TileSet.this);
			listCallback.clear();
		}
	}

}
